// pages/home/index.js
import {
  HomeModel
} from '../../model/HomeModel.js'
import {HistoryModel} from '../../model/HistoryModel.js'
const homeModel = new HomeModel()
const historyModel = new HistoryModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    postInfo: [],
    total: null,
    loading: false,
    more:true,
    searching:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    homeModel.getPosts(0).then(res => {
      this.setData({
        postInfo: res.data.postInfo,
        total: res.data.postsCount
      })
    })
  },
  onSearching(event){
    this.setData({
      searching:true
    });
  }
  ,
  onCancel(event){
    this.setData({
      searching:false
    })
  }
  ,
  onDetail(event) {
    const id = event.detail.id
    wx.navigateTo({
      url: `/pages/detail/index?id=${id}`
    })
  },
  _hasMore() {
    return this.data.postInfo.length < this.data.total
  },
  _getCurrentOffset() {
    return this.data.postInfo.length
  },
  onReachBottom: function() {
    if (!this.data.loading) {
      if (this._hasMore()) {
        this.setData({
          loading: true
        });
        homeModel.getPosts(this._getCurrentOffset()).then(res => {
          let tempArray = this.data.postInfo.concat(res.data.postInfo)
          this.setData({
            postInfo: tempArray,
            total: res.data.postsCount,
            loading: false
          })
        }, error => {
          this.setData({
            loading: false
          })
        });
      }else{
        this.setData({
          more:false
        })
      }

    }
  }
})